<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :model="filters" :inline="true">
				<el-form-item>
					<el-input v-model="filters.keywords" clearable placeholder="关键字"/>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="getCourseResourse">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addHandler" >新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="success" @click="onLineCourse" >上线</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="danger" @click="offLineCourse" >下线</el-button>
				</el-form-item>
				<!--<el-form-item>
					<el-button type="info" @click="uploadResources" >上传资源</el-button>
				</el-form-item>-->
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table @row-click="rowClick" :data="courseResource" v-loading="listLoading"
				  highlight-current-row  style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<!--索引值,为什么不用id,id不序号-->
			<el-table-column type="index" width="60">
			</el-table-column>
			<!--其他都设置值,只有一个不设置值就自动适应了-->
			<el-table-column prop="type" label="资源类型">
				<template scope="scope">
					<span v-if="scope.row.type === 0" style="color: lightslategrey;">图片</span>
					<span v-if="scope.row.type === 1" style="color: #11b95c">文件</span>
					<span v-if="scope.row.type === 2" style="color: red">视频</span>
				</template>
			</el-table-column>
			<el-table-column prop="resources" label="资源">
			</el-table-column>
			<el-table-column prop="course.name" label="课程名">
			</el-table-column>

			<el-table-column label="操作" width="200">
				<template scope="scope">
					<el-button size="small"  @click="edit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="del(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="page" :page-size="rows" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible"  :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px"  ref="addForm">

				<el-form-item label="课程名" >
					<el-select v-model="addForm.courseId" placeholder="请选择" filterable>
						<el-option
								v-for="item in courseTypes"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>


				<el-form-item label="资料类型" >
					<el-select v-model="addForm.type" placeholder="请选择" filterable>
						<el-option
								v-for="item in resourceType"
								:key="item.id"
								:label="item.name"
								:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item prop="logo" label="资源">
					<el-upload
							class="upload-demo"
							action="http://hoki-hrm.oss-cn-chengdu.aliyuncs.com"
							:data="uploadData"
							:before-upload="beforeUpload"
							:on-success="handleSuccess"
							:fileList="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" >提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import "quill/dist/quill.core.css"
	import "quill/dist/quill.snow.css"
	import "quill/dist/quill.bubble.css"
	export default {
        computed: {
			editor() {
                return this.$refs.myQuillEditor.quill
            }
		},
        components: {//使用编辑器
            quillEditor
        },
		data() {
			return {
                courseTypes:[],
                courseResource:[],
                resourceType:[
					{
					    id: '0',
						name: '图片'
					},
					{
					    id: '1',
						name: '文件'
					},
					{
					    id: '2',
						name: '视频'
					},
				], //当前页数据
                uploadData: {  //提交到OSS的参数
                    policy: '',
                    signature: '',
                    key: '',
                    ossaccessKeyId: '',
                    dir: '',
                    host: ''
                },
                courseTypeProps:{
                    value:"id",
                    label:"name"
				},
                priceDisabled:true,
                editorOption: {},//富文本编辑框配置
			    grades:[],
                charges:[
					{"id":1 , "name":"免费"},
					{"id":2 , "name":"收费"}
				],
                addFormVisible:false,
				//images:[xxx.jgp,xxxx,jpg,xxxx.jpg],
				addForm:{
                    courseId: null,
					resources: '',
					type: null
				},
                listLoading:false,
				//查询对象
				filters:{
					keywords:''
				},
				page:1,//当前页,要传递到后台的
				total:0, //分页总数
				rows: 5,
                fileList: []
			}
		},
		methods: {
            getCourseTypes(){
                this.$http.get("/course/course").then(result=>{
                    this.courseTypes = result.data;
                    console.debug(result.data);
                });
            },
            // 分页
            getCourseResourse(){
                //添加分页条件及高级查询条件
                let para = {
                    "page":this.page,
                    "keyword":this.filters.keywords,
					"rows": this.rows
                };
                this.listLoading = true; //显示加载圈
                this.$http.post("/course/courseResource/list", para).then(result=>{
                    this.total = result.data.total;
                    this.courseResource = result.data.rows;
                    console.debug(this.courseResource);
                    this.listLoading = false;  //关闭加载圈
                });
            },
            getUUID() {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";
                var uuid = s.join("");
                return uuid;
            },
            async beforeUpload(){
                await this.$http.get("/file/file/asign").then(response=>{
                    //设置相关的参数
                    var resultObj = response.data.resultObj;
                    // alert(this.uploadData.policy);
                    this.uploadData.policy = resultObj.policy;
                    // alert(this.uploadData.policy);

                    this.uploadData.signature = resultObj.signature;
                    this.uploadData.ossaccessKeyId = resultObj.accessid;
                    //上传的文件名，使用UUID处理一下
                    this.uploadData.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
                    this.uploadData.dir = resultObj.dir;
                    this.uploadData.host = resultObj.host;
                });
            },
            handleSuccess(res, file) {
                console.debug(file);
                console.debug(res);
                //上传的完整的文件地址
				var urlPath = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}",file.name) ;
				this.addForm.resources += urlPath + " ";
                this.addForm.resources.trim();
				console.debug(this.addForm.resources);
                this.$message({message: '上传成功，图片地址：', type: 'success' });
            },
            addSubmit(){
                /*this.addForm.courseTypeId = this.addForm.courseTypeId[this.addForm.courseTypeId.length - 1];
				/!**

                chargeId: 2
                description: "1111"
                gradeId: 1
                intro: "<p>111<img src=""
                price: "1111"
                qq: "111"
                forUser: "1"
				 **!/
				var gradeName;
				for(var i = 0 ; i < this.grades.length ; i++){
                    var grade = this.grades[i];
                    if(grade.id === this.addForm.gradeId){
                        gradeName = grade.name;
                        break;
					}
				}*/

                this.$http.put("/course/courseResource",this.addForm).then(res=>{
                    var ajaxResult = res.data;
                    if(ajaxResult.success){
                        this.$message({
                            message: '保存成功!',
                            type: 'success'
                        });
                        this.addFormVisible = false;
                        this.getCourseResourse();
                    }else{
                        this.$message({
                            message: '上传失败!',
                            type: 'error'
                        });
                    }
				});
			},
            // 5.删除单条数据
            del(row) { // index是数据的下标, row是具体数据,其中包含id
                // console.debug(row)
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    // 发送请求删除传回id
                    this.$http.delete("/course/courseResource/" + row.id).then(res => {
                        let{success, message} = res.data;
                        if (success) { // 成功提示信息
                            this.$message({
                                type: 'success',
                                message: message
                            });
                            // 并且重新设置currentPage
                            let totalPage = Math.ceil((this.total - 1) / this.rows); // 删除一条后的总页数
                            // 如果当前页大于总页数,重新设置设置当前页为总页数(翻到上一页)
                            this.page = this.page > totalPage ? totalPage : this.page;
                            // 如果当前页小于1了,删除完了,自动保持在第一页
                            this.page = this.page < 1 ? 1 : this.page;
                        } else {
                            // 失败提示信息
                            this.$message.error({
                                type: 'warning',
                                message: '删除异常'
                            });
                        }
                        // 最后重新加载页面
                        this.getCourseResourse();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            changeCharge(chargeId){
                console.log(chargeId);
                if(chargeId === 1){
                    this.priceDisabled = true;
                    this.addForm.price = "";
                    this.addForm.priceOld = "";
				}else{
                    this.priceDisabled = false;
				}
			},
            onEditorReady(editor) {
                //当富文本编辑框初始化好执行
            },
            addHandler(){
                this.getCourseResourse();
                this.addForm.courseId = null;
                this.addForm.type = null;
                this.fileList=null
                this.fileList = [];
                this.addFormVisible = true;
			},
            edit(row) { // index数据编号/下标(不是id), row是具体数据包含id
                // 清空表单
				console.debug(row);
                this.addForm = {
                    courseId: null,
                    type: null,
                    resources: "", // 多张图片
                };
                // 清空图片
                this.fileList = [];
                // 回显数据,row里面包含id,所以回显后,this.saveForm就有id了
                this.addForm.courseId = row.course.id;
                this.addForm.type = row.type;
                // 回显图片
                let picArr = row.resources.split(" ");
                console.debug(picArr);
                // console.debug(row.resources)
                // console.debug(picArr);
                if (row.resources !== "") {
                    for (var i = 0; i < picArr.length - 1; i++) {
                        this.fileList.push({
                            name: '图片' + (i + 1),
                            url: picArr[i]
                        });
                    }
                }
                // console.debug(this.fileList);
                // 点击编辑弹出编辑界面
                this.addFormVisible = true;
            },
            handleCurrentChange(currentPage){
                this.page = currentPage;
                this.getCourseResourse();
			},
            rowClick(row){
				this.row = row;
				console.log(this.row);
			},
            //性别显示转换
            statusFormatter: function (row, column) {
                return row.status == 1 ? '已上线' : '未上线';
            },
		},
		mounted() {
		    // this.getCourses();
		    // this.getGrades();
		    this.getCourseResourse();
		    this.getCourseTypes();
		}
	}

</script>

<style scoped>

</style>